#include "activity_module.h"

#include "../share/tplmgr.h"
#include "../share/time_module.h"
#include "../share/activity_config.h"
#include "scene_event.h"
#include "GameServer.h"
#include "../share/MessageDef.h"
#include "Player.h"

bool CActivityModule::Init( )
{
	registe_client_msg(activity_player_info_request, CActivityModule::OnMsgPlayerActivityInfoRequest);
	return true;
}

bool CActivityModule::Finalize( )
{
	return true;
}

bool CActivityModule::IsActivityOpen( int32_t activity_id )
{
    return ( std::find( opened_activity_list_.begin( ), opened_activity_list_.end( ), activity_id ) != opened_activity_list_.end( ) );
}

int32_t CActivityModule::GetNextFireTime( int32_t activity_id )
{
    const CActivityTpl* activity_tpl = CTPLManager::GetInstance( ).activity_config( ).GetActivityByID( activity_id );
    if( NULL == activity_tpl )
    {
        return 0;
    }
    return activity_tpl->GetNextFireTime( );
}

void CActivityModule::TickUpdate( )
{
	time_t cur_sec = CUR_SEC;
	if( cur_sec <= update_time_ ) {
		return;
	}
	tm* cur_tm = localtime( &cur_sec );
	if( NULL == cur_tm )
	{
		return;
	}
	TActivityIDList old_activity_list = opened_activity_list_;
	opened_activity_list_.clear( );
	const CActivityConfig& activity_config = CTPLManager::GetInstance( ).activity_config( );
	const CActivityConfig::TActivityMap& activity_map = activity_config.activity_map( );
	for( CActivityConfig::TActivityMap::const_iterator iter = activity_map.begin( ); iter != activity_map.end( ); ++iter )
	{
		const CActivityTpl& activity_tpl = iter->second;
		if( activity_tpl.IsOpen( *cur_tm ) != true )
		{
			continue;
		}
		opened_activity_list_.push_back( activity_tpl.activity_id( ) );
	}

	//对比两次的活动
	std::vector< int32_t > activity_start;
	std::vector< int32_t > activity_end;
	std::set_difference( opened_activity_list_.begin( ), opened_activity_list_.end( ), old_activity_list.begin( ), old_activity_list.end( ), std::back_inserter( activity_start ) );
	std::set_difference( old_activity_list.begin( ), old_activity_list.end( ), opened_activity_list_.begin( ), opened_activity_list_.end( ), std::back_inserter( activity_end ) );
	for( std::vector< int32_t >::iterator iter = activity_start.begin( ); iter != activity_start.end( ); ++iter )
	{
		LOG_DEBUG("default","activity start : %d", *iter );
		activity_start_event( *iter );
	}
	for( std::vector< int32_t >::iterator iter = activity_end.begin( ); iter != activity_end.end( ); ++iter )
	{
		LOG_DEBUG("default", "activity end : %d", *iter );
		activity_end_event( *iter );
	}
	update_time_ = cur_sec;
}

void CActivityModule::OnMsgPlayerActivityInfoRequest(Player& player, const CJsonMessageBase& msg)
{
	Json::Value response;
	response["msgid"] = activity_player_info_response;
	response["ret"] = ::common::SUCCEED;
	
	Json::Value activity;
	player.role_activity().WriteToJson(activity);
	response["activity"] = activity;

	player.SendToClient(response, activity_player_info_response);
}
